/**
 * Created by AllanXu on 01/03/2016.
 */
define(function (require) {
	var Vue = require('vue'),
		moment = require('moment'),
		Config = require('config'),
		_ = require('ajax'),
		utilities = require('utilities'),
		id = sessionStorage.id;

	var app = new Vue({
		el: '#uc_basicInfo',
		data: {
			str: '',
			selections: {
				424: []
			},
			cityList: [],
			regionList: [],
			xregionNum: 0,
			req: {
				'name': '',
				'nickName': '',
				'cregion_id': '',
				'xregion_id': '',
				'birth': '',
				'height': '',
				'weight': '',
				'age': '',
				'nativePlace': '',
				'money': '',
                'zy': '',
				'zodiac': '',
				'constellation': '',
				'blood': '',
                'sfrz': '',
				'education': '',
				'marry': '',
				'nation': '',
				'children': '',
				'car': '',
                'idCard': '',
                'company': '',
				'room': ''
			}
		},
		methods: {
			loadArea: function (arrName, code, callback) {
				_(Config.SERVICE.COMMON.ADDRLIST, {
					parentId: code
				}, function (data) {
					app[arrName] = data.obj[code];
					app[arrName].unshift({id: '', name: '请选择'});
					var ifxr = false
					for (var a = 0; a < data.obj[code].length; a++) {
						if (app.req.xregion_id == data.obj[code][a].id) {
							ifxr = true;
							break;
						}
					}
					if (ifxr == false && app.xregionNum > 0) {
						app.req.xregion_id = ''
					}
					app.xregionNum++
					});
					if (typeof callback === 'function')
						callback();
			},
			init: function () {
				// 加载select项
				_(Config.DICTIONARY, {
					parentId: '418,424,437,450,8,6,7,457,463,467,1010,975'
				}, function (data) {
					for (var key in data.obj) {
						data.obj[key].unshift({id: '', name: '请选择'});
					}
					app.selections = data.obj;

					// refill
					_(Config.SERVICE.USERCENTER.MEMBER_DETAIL, {
						id: id
					}, function (data) {
						for (var key in app.req) {
							app.req[key] = data.obj.member[key];
						}
						if(data.obj.member.cregion!=null){
							app.req.cregion_id = data.obj.member.cregion.id;
							app.req.xregion_id = data.obj.member.xregion.id;
                        }
						// 生日
						if(data.obj.member.birth !== '' && data.obj.member.birth !== null)
							app.req.birth = data.obj.member.birth.split(' ')[0];
						else {
							app.req.birth = moment(new Date()).format('YYYY-MM-DD');
						}
						app.req.age = data.obj.member.age != 0 ? data.obj.member.age : '';

						app.req.height = app.req.height == 0 ? '' : app.req.height;

						app.loadArea('cityList', 2);
						if(app.req.cregion_id!=null){
                            app.loadArea('regionList', app.req.cregion_id);
						}
					});
				});
			},
			save: function () {
//              console.log(app.req.xregion_id);
                for (var key in app.req) {
                	if(key!='age' && key!='birth'&& key!='zodiac'&& key!='constellation'){
                		console.log(key, 'key')
                        if (app.req[key] === ''){
                        	if (key == 'name') {
                        		alert('请填写姓名!');
                        	} else if (key == 'idCard') {
                        		alert('请填写身份证号!')
                        	} else if (key == 'nickName') {
                        		alert('请填写昵称!')
                        	} else if (key == 'cregion_id') {
                        		alert('请选择所属组织!')
                        	} else if (key == 'xregion_id') {
                        		alert('请选择所属组织!')
                        	} else if (key == 'height') {
                        		alert('请填写身高!')
                        	} else if (key == 'weight') {
                        		alert('请填写体重!')
                        	}else if (key == 'nativePlace') {
                        		alert('请选择籍贯!')
                        	} else if (key == 'money') {
                        		alert('请选择月薪!')
                        	} else if (key == 'zy') {
                        		alert('请选择职业!')
                        	} else if (key == 'education') {
                        		alert('请选择学历!')
                        	} else if (key == 'marry') {
                        		alert('请选择婚姻状态!')
                        	} else if (key == 'company') {
                        		alert('请填写工作单位!')
                        	}
                        	return;
                        }
					}
                }

				var req = {};
				for (var key in app.req) {
					if (key !== 'cregion_id' && key !== 'xregion_id')
						req['xgmember.' + key] = app.req[key];
					if(key=='idCard')
						if(this.IdentityCodeValid(app.req[key])==false){
							return;
						}
				}
				req['xgmember.cregion.id'] = app.req.cregion_id;
				req['xgmember.xregion.id'] = app.req.xregion_id;
				req.id = id;
				console.log(req);

				_(Config.SERVICE.USERCENTER.BASIC_INFO_JB_SAVE, req, function (data) {
					if (data.code == 200 && data.type === 'SUCCESS') {
						alert('保存成功！');
						utilities.refreshUserInfo(function (data) {
							history.back();
						});
					}
				});
			},
			getName: function (arr, id) {
				for (var i = 0; i < arr.length; i++)
					if (arr[i]['id'] == id)
						return arr[i]['name'];
			},
            IdentityCodeValid:function (code) {
                num = code.toUpperCase();
                //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X。
                if (!(/(^\d{15}$)|(^\d{17}([0-9]|X)$)/.test(num)))
                {
                    alert('输入的身份证号长度不对，或者号码不符合规定！');
                    return false;
                }
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                //下面分别分析出生日期和校验位
                var len, re;
                len = num.length;
                if (len == 15)
                {
                    re = new RegExp(/^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/);
                    var arrSplit = num.match(re);

                    //检查生日日期是否正确
                    var dtmBirth = new Date('19' + arrSplit[2] + '/' + arrSplit[3] + '/' + arrSplit[4]);
                    var bGoodDay;
                    bGoodDay = (dtmBirth.getYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
                    if (!bGoodDay)
                    {
                        alert('输入的身份证号里出生日期不对！');
                        return false;
                    }
                    else
                    {
                        //将15位身份证转成18位
                        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                        var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                        var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                        var nTemp = 0, i;
                        num = num.substr(0, 6) + '19' + num.substr(6, num.length - 6);
                        for(i = 0; i < 17; i ++)
                        {
                            nTemp += num.substr(i, 1) * arrInt[i];
                        }
                        num += arrCh[nTemp % 11];

                    }
                }
                if (len == 18)
                {
                    re = new RegExp(/^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/);
                    var arrSplit = num.match(re);

                    //检查生日日期是否正确
                    var dtmBirth = new Date(arrSplit[2] + "/" + arrSplit[3] + "/" + arrSplit[4]);
                    var bGoodDay;
                    bGoodDay = (dtmBirth.getFullYear() == Number(arrSplit[2])) && ((dtmBirth.getMonth() + 1) == Number(arrSplit[3])) && (dtmBirth.getDate() == Number(arrSplit[4]));
                    if (!bGoodDay)
                    {
                        alert('输入的身份证号里出生日期不对！');
                        return false;
                    }
                    else
                    {
                        //检验18位身份证的校验码是否正确。
                        //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                        var valnum;
                        var arrInt = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                        var arrCh = new Array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                        var nTemp = 0, i;
                        for(i = 0; i < 17; i ++)
                        {
                            nTemp += num.substr(i, 1) * arrInt[i];
                        }
                        valnum = arrCh[nTemp % 11];
                        if (valnum != num.substr(17, 1))
                        {
                            alert('18位身份证的校验码不正确！应该为：' + valnum);
                            return false;
                        }

                    }
                }
                return true;
            }
		}
	});

	app.init();
});
